package user

import (
	"context"
	"encoding/json"

	"googee/service/admin/api/internal/svc"
	"googee/service/admin/api/internal/types"
	"googee/service/admin/rpc/sys"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogoutLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLogoutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoutLogic {
	return &LogoutLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LogoutLogic) Logout(req *types.LogoutReq, ip string) (resp *types.LogoutResp, err error) {
	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	u, _ := l.svcCtx.Sys.UserInfo(l.ctx, &sys.InfoReq{
		UserId: id,
	})

	//保存登录日志
	_, _ = l.svcCtx.Sys.LoginLogAdd(l.ctx, &sys.LoginLogAddReq{
		UserName: u.Name,
		Status:   "logout",
		Ip:       ip,
		CreateBy: u.Name,
	})

	resp = &types.LogoutResp{}
	resp.Code = "000000"
	resp.Message = "登出成功"
	return
}
